package com.jumaojiang.controller;

import com.alibaba.fastjson.JSONObject;
import com.jumaojiang.mapper.JeeUserMapper;
import com.jumaojiang.pojo.JeeUser;
import com.jumaojiang.service.UserService;
import com.jumaojiang.service.WxPusherAuthService;
import com.jumaojiang.utils.JWTUtil;
import com.jumaojiang.vo.AjaxResultVo;
import com.jumaojiang.wxpusher.bean.callback.BaseCallBackReq;
import com.jumaojiang.wxpusher.bean.callback.CallBackData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.*;

/**
 * forward
 *
 * @author wuhanwei
 * @version 1.0
 * @date 2021/11/4
 */
@Controller
@ResponseBody
public class WxPusherAuthController {

    /**
     * 登陆请求返回的参数:
     *       qrCodeUrl: 二维码地址
     *       authCode : 服务器生成的验证码
     */

    @Autowired
    private UserService userService;

    @Autowired
    private WxPusherAuthService wxPusherAuthService;

    @Autowired
    private ThreadPoolData threadPoolData;

    @Autowired
    private JeeUserMapper jeeUserMapper;

    // 接收wxpusher的回调,用户扫码成功后,wxpusher会发送用户信息给服务器
    @RequestMapping("/jee-wxpusher/jee-callback")  // BaseCallBackReq callBackReq,
    public String callback(@RequestParam(value = "requestBody", required = false) String requestBody) {
        String s1 = requestBody.split("\"data\":")[1];
        String substring = s1.substring(1, s1.length() - 2).replaceAll("\"","");
        String[] split1 = substring.split(",");
        CallBackData callBackData = new CallBackData();
        for (String s : split1) {
            switch(s.split(":")[0]){
                case "userName":
                    callBackData.setUserName(s.replace("userName:",""));
                    break;
                case "userHeadImg":
                    callBackData.setUserHeadImg(s.replace("userHeadImg:",""));
                    break;
                case "uid":
                    callBackData.setUid(s.replace("uid:",""));
                    break;
                case "time":
                    callBackData.setTime(s.replace("time:",""));
                    break;
                case "source":
                    callBackData.setSource(s.replace("source:",""));
                    break;
                case "id":
                    callBackData.setId(s.replace("id:",""));
                    break;
                case "extra":
                    callBackData.setExtra(s.replace("extra:",""));
                    break;
                case "appName":
                    callBackData.setAppName(s.replace("appName:",""));
                    break;
                case "appKey":
                    callBackData.setAppKey(s.replace("appKey:",""));
                    break;
                case "appId":
                    callBackData.setAppId(s.replace("appId:",""));
                    break;
            }
        }
//        // 将用户数据暂存入缓存,有效期5分钟,extra即服务器生成下发给wxpusher的authCode
//        wxPusherAuthService.saveAuthUserMsg(callBackData.getExtra(), callBackData);
        // 获取查询阻塞等待的线程数据
        ThreadPoolData.UserData threadData = threadPoolData.getThreadData(callBackData.getExtra());
        // 存入callBackData
        threadData.setCallBackData(callBackData);
        // 唤醒线程
        threadData.getThread().interrupt();
        // 直接返回 空串即可
        return "";
    }

    // 用户登陆验证
    @RequestMapping("/jee-wxpusher/jee-verify")
    public AjaxResultVo verify(@RequestParam(value = "authCode", required = false) String authCode,
                             @RequestParam(value = "registration", required = false) String registration,
                             HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 存储当前线程
        Thread thread = Thread.currentThread();
        ThreadPoolData.UserData userData = new ThreadPoolData.UserData();
        userData.setThread(thread);
        threadPoolData.setThreadData(authCode, userData);
        // 阻塞当前线程, 等待callback唤醒, 5分钟超时
        try {
            Thread.sleep(5*60*1000);
        } catch (InterruptedException e) {}
        // 从线程池数据库中获取用户数据
        CallBackData callBackData = threadPoolData.getThreadData(authCode).getCallBackData();
        if(callBackData != null){
            JeeUser user = userService.login(request, callBackData, registration);
            if(user == null){
                return new AjaxResultVo(401, "用户登录失败", null);
            }
            // 生成jwtToken, 存入cookie
            String jwtToken = wxPusherAuthService.createJwtTokenAndSaveCookie(request, response, user);
            if( jwtToken != null && jwtToken.length() > 10 ){
                threadPoolData.removeMap(authCode);
                // 此处用户注册或用户登陆,写入cookie成功
                return new AjaxResultVo(jwtToken);
            }
        }
        return new AjaxResultVo(401, "用户登录失败", null);
    }

    // 用户请求登陆
    @RequestMapping("/jee-wxpusher/jee-login")
    public AjaxResultVo login(){
        // 生成authCode
        String authCode = UUID.randomUUID().toString().replaceAll("-", "");
        // 获取二维码地址
        String qrCodeUrl = wxPusherAuthService.getQRCodeUrl(authCode);
        if(qrCodeUrl != null){
            Map<String, String> map = new HashMap<>();
            map.put("qrCodeUrl",qrCodeUrl);
            map.put("authCode", authCode);
            return new AjaxResultVo(map);
        }
        // wxpusher内部错误
        return new AjaxResultVo(500, "服务器内部错误,请稍后再试!");
    }

    // 判断是否登录
    @RequestMapping("/is-login-test")
    public AjaxResultVo testLogin(HttpServletRequest request){
        Integer userId = JWTUtil.parseUserId(request);
        JeeUser jeeUser = new JeeUser();
        jeeUser.setUserId(userId);
        jeeUser.setUserLastLoginTime(new Date());
        jeeUserMapper.updateByPrimaryKeySelective(jeeUser);
        // 未登录会被拦截处理
        return new AjaxResultVo();
    }
}





















